<template>
  <view class="content"  >
    <u-navbar title="登录" height="50"></u-navbar>
    <view class="common_sort_search_layout">
      <view
        :class="['sort-button', showType == 'sort' ? 'sort-active' : '']"
        @click="showSort"
      >
        <span>排序</span>
        <img src="../../static/sort.png" alt="" />
      </view>
      <view
        :class="['sift-button', showType == 'sift' ? 'sort-active' : '']"
        @click="showSift"
      >
        <span>筛选</span>
        <img src="../../static/sift.png" alt="" />
      </view>
    </view>
    <view class="manage-list-box">
      <u-list class="srollview" @scrolltolower="scrolltolower" style="padding-top: 10px" :scrollable="false">
        <u-list-item v-for="(item, index) in manageList" :key="index">
          <view class="list-item">
            <view class="item-top">
              <view class="item-name">
                <span>{{ item.customerName }}</span
                >{{ GENDER_CODE[item.gender] || item.gender }}
              </view>
              <view class="item-status">
                <span
                  class="status-point"
                  :style="{ backgroundColor: getColor(item.caseStatus) }"
                ></span>
                <span class="status-txt">{{
                  getStatusStr(item.caseStatus)
                }}</span>
              </view>
            </view>
            <view class="copy-box">
              <u-icon name="order"></u-icon>
              <span style="margin-left: 5px">{{ item.applyNo }}</span>
              <span
                style="color: red; margin-left: 10px"
                @click="copy(item.applyNo)"
                >[复制]</span
              >
            </view>
            <!-- 单位名称 -->
            <view class="address-box">
              <view class="unit-name">
                <u-icon name="home"></u-icon>{{ encordCompanyName(item.organName) }}
              </view>
              <view class="unit-address">
                <u-icon name="map"></u-icon>{{ item.organProvince + '-' + item.organCity + '-' +item.organTown }}
              </view>
            </view>
            <u-divider></u-divider>
            <view class="item-bottom">
              <view class="time-box">
                <u-icon name="clock"></u-icon>
                {{ item.createTime }}
              </view>
              <view class="item-btn-box">
                <view
                  class="call-client"
                  v-if="isShowCall(item)"
                  @click="call(item.customerPhone)"
                  >联系客户</view
                >
                <view
                  class="func-type"
                  v-if="item.caseStatus == 'APPLY_CONFIRM' || item.caseStatus == 'WAIT_AMEND'"
                  @click="toConfirm(item.caseId)"
                  >确认资料</view
                >
                <view
                  class="func-type"
                  v-if="
                    item.caseStatus == 'PRE_CONFIRM' ||
                    item.caseStatus == 'BACK_PATCH'
                  "
                  @click="
                    toPatch(item.caseStatus == 'PRE_CONFIRM', item.caseId, item.projectNo)
                  "
                  >补充资料</view
                >
                <view class="show-order" @click="toDtail(item.caseId)"
                  >查看</view
                >
              </view>
            </view>
          </view>
        </u-list-item>
        <view style="margin-bottom: 10px">
          <u-loadmore v-if="true" :status="loadMoreStatus"
           :loadmoreText="'上拉或点击加载更多'" 
           :loadingText="'正在加载'"
           :nomoreText="'暂无更多数据'"
          />
        </view>
      </u-list>
    </view>
    <home-window
      :showType="showType"
      :selectedObj="searchObject"
      v-if="isShowSort"
      @submitCallBack="onSubmitCallBack"
    ></home-window>
  </view>
</template>

<script>
import { CASE_STATUS } from "../../common/js/constant";
import HomePop from "../../components/HomePop/HomePop.vue";
import ajax from "../../api/ajax";
import { aesDecrypt } from "../../common/js/crypto";
import { attestationCode, rsadecryptData } from "../../common/js/rsa";
import { SUCCESS_STATUS } from "../../common/js/constant";
import { copyText, desensitizationText, getAddress, msg, showLoading, hideLoading } from "../../common/js/util";
import HomeWindow from "../../components/HomePop/HomeWindow.vue";

export const GENDER_CODE = {
  'M': '先生',
  'F': '女士'
}

export default {
  data() {
    return {
      loadMoreStatus: '', // nomore loading
      GENDER_CODE,
      CASE_STATUS,
      isShowSort: false,
      showType: "",
      searchObject: {
        // 查询条件
        productType: 'JXD',
        menuFlag: '1',
        beginTime: "", // 开始时间
        endTime: "", // 结束时间
        caseStatus: "", // 申请状态
        freeCondition: "", // 自由条件
        pageNum: 1,
        pageSize: 10,
        sortField: "create_time", // 排序字段
        sortType: "desc", //排序方式
      },
      pages: 0, // 总页数
      toScrollTop: 0,
      manageList: [],
      isLoading: false, // 是否正在请求数据
      isToListAndRefresh: false,
    };
  },
  components: {
    HomePop,
    HomeWindow,
  },
  onLoad: function (option) {
    if (option) {
      // 缓存token
      console.log('onLoad请求路径：'+JSON.stringify(option));
      if (option.token) {
        uni.setStorageSync("token", option.token);
        console.log('>>>>>>保存token');
      }
    }
    // 注册监听
    uni.$on('refreshConfirmDetail', this.notifyRefresh)
    uni.$on('refreshList', this.notifyRefresh)
  },
  onPullDownRefresh() {
    this.onRefresh();
  },
  created() {
    this.searchObject.pageNum = 1;
    this.getList();
  },
  mounted () {
    window.patchSuccessRefresh = this.patchSuccessRefresh;
  },
  methods: {
    // 贷前调查处理完成，刷新列表
    notifyRefresh (e) {
      this.searchObject.pageNum = 1;
      this.getList();
    },
    // 脱敏单位名称
    encordCompanyName (name) {
      return desensitizationText(name)
    },
    patchSuccessRefresh () {
      // 补件完成。更新列表
      this.searchObject.pageNum = 1;
      this.getList();
    }, 
    // 搜索
    toSearch() {
      if (this.isLoading){
        msg('加载中，请稍后！')
        return
      }
      this.searchObject.pageNum = 1;
      this.getList();
    },
    // 联系客户
    call(phone) {
      esale.toCall(phone.toString());
    },
    onBack() {
      esale.onBack();
    },
    getColor(status) {
      if (CASE_STATUS[status]) {
        return CASE_STATUS[status].color;
      } else {
        return "#58a3f7";
      }
    },
    getStatusStr(status) {
      if (CASE_STATUS[status]) {
        return CASE_STATUS[status].type;
      } else {
        return "未知";
      }
    },
    /**
     * 补件
     * @param {*} isNoBack 是否不是退回补件
     */
    toPatch(isNoBack, caseId, projectNo) {
      console.log('....... caseId'+caseId);
      if (isNoBack) {
        // 进件补件
        esale.toPatch(caseId, 1, projectNo);
      } else {
        // 退回补件
        esale.toBackPatch(caseId, 1);
      }
    },
    /**
     * 信息确认
     */
    toConfirm(caseId) {
      uni.navigateTo({
        url: `/pages/ConfirmAppInformation/index?id=${caseId}`,
      });
    },
    // 是否显示联系客户
    isShowCall(item) {
      return (
        item.caseStatus != "AUDIT_REJECT" ||
        item.caseStatus != "APPLY_CANCEL" ||
        item.caseStatus != "RESEARCH"
      );
    },
    // 地址转换
    formartAddress(address) {
      return getAddress(address);
    },
    copy(applyNo) {
      var result = copyText(applyNo);
      msg(result ? "复制成功" : "复制失败")
    },
    // 下拉刷新
    onRefresh() {
      this.searchObject.pageNum = 1;
      if (!this.triggered) {
        this.triggered = true;
        this.getList();
      }
    },
    // 获取列表数据
    getList() {
      showLoading()
      this.isLoading = true
      let data = {...this.searchObject}
      data.productType = this.searchObject.productType
      data.beginTime = this.searchObject.beginTime ? this.searchObject.beginTime+ ' 00:00:00' : ''
      data.endTime = this.searchObject.endTime ? this.searchObject.endTime+ ' 23:59:59' : ''
      console.log('参数：'+JSON.stringify(data));
      ajax
        .getCaseList(data)
        .then((res) => {
          const {
            responseHead: { responseCode, responseMsg, random = "", sign = "" },
            responseBody = {},
          } = res;
          this.triggered = false;
          this.isLoading = false
          uni.stopPullDownRefresh();
          hideLoading()
          if (responseCode === SUCCESS_STATUS) {
            let bsign = `responseCode=${responseCode}responseMsg=${responseMsg}${responseBody}`;
            let data = aesDecrypt(responseBody, rsadecryptData(random))
              ? JSON.parse(aesDecrypt(responseBody, rsadecryptData(random)))
              : {};
            console.log("解密后内容： " + JSON.stringify(data));
            if (attestationCode(bsign, sign)) {
              this.pages = data.pages || 0;
              let arr = data.list || []
              if (this.searchObject.pageNum == 1) {
                this.manageList = arr
              } else {
                arr.forEach(element => {
                  this.manageList.push(element)
                });
              }
            }
          } else {
            console.log("【接口回调】: "+responseCode +" , " +responseMsg);
            msg(responseCode + ":" + responseMsg);
          }
        })
        .catch(() => {
          console.log("catch>>>>");
          this.triggered = false;
          this.isLoading = false
          hideLoading()
          uni.stopPullDownRefresh();
        });
    },
    // 加载更多
    scrolltolower() {
      if (!this.isLoading) {
        this.loadMoreStatus = 'loading'
        this.searchObject.pageNum++ ; 
        console.log(" scrollToBottom滚动到底部: >>>>>"+this.searchObject.pageNum);
        if (this.searchObject.pageNum <= this.pages) {
          this.getList();
        } else {
          this.searchObject.pageNum = this.pages+1
          this.loadMoreStatus = 'nomore'
          msg('暂无更多数据')
        }
      }
    },
    // 搜索筛选回调
    onSubmitCallBack(obj) {
      this.isShowSort = false;
      this.showType = "";
      console.log(">>>>>回调: ", obj);
      this.manageList = []
      this.searchObject.pageNum = 1
      this.getList()
    },
    showSort() {
      this.showType = "sort";
      this.isShowSort = true;
    },
    showSift() {
      this.showType = "sift";
      this.isShowSort = true;
    },
    toDtail(caseId) {
      console.log('>>>>>>>详情ID:'+caseId);
      uni.navigateTo({
        url: `/pages/CaseDetail/index?id=${caseId}`,
      });
    }
  },
  watch: {
    isToListAndRefresh : {
      handler: function(e) {
        if (e) {
          this.patchSuccessRefresh()
          this.isToListAndRefresh = false
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.content {
  margin-top: 50px;
  width: 100%;
  position: absolute;
  height: calc(100vh - 50px);
  overflow: hidden;
  .manage-list-box {
    width: 100%;
    height: calc(100vh - 146px);
    background-color: #e4e3e3;
    box-sizing: border-box;
    padding: 0 10px;
    overflow-x: hidden;
    overflow-y: auto;
    .srollview {
      height: 82vh !important;
    }
    .list-item {
      width: 100%;
      box-sizing: border-box;
      padding: 15px 10px;
      border-radius: 5px;
      background-color: #fff;
      margin-bottom: 25rpx;
      .item-top {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15rpx;
        .item-name {
          font-size: 26rpx;
          span {
            font-weight: bold;
            font-size: 30rpx;
            padding-right: 15rpx;
          }
        }
        .item-status {
          font-size: 26rpx;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          .status-point {
            display: inline-block;
            width: 15rpx;
            height: 15rpx;
            border-radius: 50%;
            margin-right: 15rpx;
          }
        }
      }
      .copy-box {
        width: 100%;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        font-size: 26rpx;
        margin-bottom: 20rpx;
        .copy-btn {
          color: red;
          margin-left: 10rpx;
        }
      }
      .address-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 26rpx;
        .unit-name,
        .unit-address {
          display: flex;
          justify-content: flex-start;
          align-items: center;
        }
      }
      .item-bottom {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 26rpx;
        .time-box {
          display: flex;
          justify-content: flex-start;
          align-items: center;
        }
        .item-btn-box {
          display: flex;
          justify-content: flex-end;
          align-items: center;
          color: red;
          .call-client,
          .func-type {
            margin-right: 20rpx;
            font-size: 26rpx;
          }
        }
      }
    }
  }
}
</style>
